﻿import axios from 'axios'
import router from '../router/index.js'
import {MessageBox} from 'element-ui'
import store from '../store/index.js'
import comFunc from '../common_js/comFunc.js'

axios.defaults.timeout = 240000
// axios.defaults.baseURL = process.env.CENTER_API
// axios.defaults.headers.post['content-Type'] = 'application/x-www-form-urlencoded'
/* global $URL */

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (sessionStorage.getItem('token') && config.url && config.url.indexOf($URL.IMG_UPLOAD_URL) === -1) {
    config.headers.common['Authorization'] = 'Bearer ' + sessionStorage.getItem('token')
  }
  if (sessionStorage.getItem('fileToken') && config.url && config.url.indexOf($URL.IMG_UPLOAD_URL) !== -1) {
    config.headers.common['Authorization'] = 'Bearer ' + sessionStorage.getItem('fileToken')
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  store.dispatch('changeRequestCounts', parseInt(store.state.hadRequestError) + 1)
  if (store.state.hadRequestError === 1) {
    if (error.response.status === 401) {
      if (error.response.data.error) {
        if (error.response.data.error.indexOf('TimeOut') >= 0) {
          MessageBox.alert('登录超时，请重新登录！', '提示', {
            confirmButtonText: '确定',
            showClose: false,
            callback: () => {
              // 退出登录时，跳转到登录页面
              router.push('/')
              store.dispatch('logout')
            }
          })
        }
      }
    } else if (error.response.status === 403) {
      MessageBox.alert('该账号没有本功能的操作权限，请联系管理员设置', '提示', {
        confirmButtonText: '确定',
        showClose: false,
        callback: () => {
          router.go(-1)
        }
      })
    }
  }
  return Promise.reject(error)
})
function encryptData (data) {
  if (store.state.isHttpEncrypt) {
    let nonce_str = comFunc.getNonceStr()
    let content_key = comFunc.encryptAES(nonce_str, store.state.shareKey)
    let content = {
      data: comFunc.encryptAES(data, content_key),
      nonce_str: nonce_str
    }
    return {
      data: comFunc.encryptAES(content, store.state.shareKey)
    }
  } else {
    return data
  }
}
function decryptData (data) {
  if (store.state.isHttpEncrypt) {
    let content = JSON.parse(comFunc.decryptAES(data, store.state.shareKey))
    if (content && content.data && content.nonce_str) {
      let nonce_str = content.nonce_str
      let content_key = comFunc.encryptAES(nonce_str, store.state.shareKey)
      let rtn = comFunc.decryptAES(content.data, content_key)
      if (rtn.startsWith('{')) {
        return JSON.parse(rtn)
      } else if (rtn.startsWith('[')) {
        return JSON.parse(rtn)
      } else {
        return rtn
      }
    } else {
      return null
    }
  } else {
    return data
  }
}
// 注：接口的基础地址主要分为：业务地址（$URL.CENTER_API）和流程地址（$URL.WORKFLOW_API）
// 其中：
// -----1、业务地址对应的api，均为传统的 post/patch/$delete/get 方法
// -----2、基础流程对应的api，均为传统的 basicWFPost/basicWFPatch/basicWFDelete/basicWFGet 方法
// -----3、流程执行对应的api，目前只有一个 workflowPost方法（请求头ApplicationToken，ApplicationCode）

// post方法
export function post (url, data = {}, header = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.CENTER_API + url,
      method: 'post',
      data: encryptData(data),
      headers: header
    }).then(response => {
      if (store.state.isHttpEncrypt) {
        let re = {}
        Object.assign(re, response)
        if (re.data.result) {
          re.data.result = decryptData(re.data.result.data)
        } else {
          re.data = decryptData(re.data.data)
        }
        resolve(re)
      } else {
        resolve(response)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

// 流程部分的post方法
export function basicWFPost (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.WORKFLOW_API + url,
      method: 'post',
      data
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

// 流程图中的post方法（主要用在流程执行的excute的方法，以及流程执行中选人）
export function workflowPost (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.WORKFLOW_API + url,
      method: 'post',
      data,
      headers: {
        'ApplicationToken': $URL.ApplicationToken,
        'ApplicationCode': $URL.ApplicationCode
      }
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

// get方法
export function get (url, params = {}, header = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.CENTER_API + url,
      method: 'get',
      params,
      headers: header
    }).then(response => {
      if (url === '/_init') {
        resolve(response)
      } else {
        if (store.state.isHttpEncrypt) {
          let re = {}
          Object.assign(re, response)
          if (re.data.result) {
            re.data.result = decryptData(re.data.result.data)
          } else {
            re.data = decryptData(re.data.data)
          }
          resolve(re)
        } else {
          resolve(response)
        }
      }
    }).catch(error => {
      reject(error)
    })
  })
}

// 流程部分的get方法
export function basicWFGet (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.WORKFLOW_API + url,
      method: 'get',
      params
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

// delete方法
export function $delete (url, params = {}) {
  let p = {}
  if (params.data) {
    p.data = encryptData(params.data)
  } else {
    p = params
  }
  return new Promise((resolve, reject) => {
    axios.delete(
      $URL.CENTER_API + url, p
    ).then(response => {
      if (store.state.isHttpEncrypt) {
        let re = {}
        Object.assign(re, response)
        if (re.data.result) {
          re.data.result = decryptData(re.data.result.data)
        } else {
          re.data = decryptData(re.data.data)
        }
        resolve(re)
      } else {
        resolve(response)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

// 流程部分的delete方法
export function basicWFDelete (url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(
      $URL.WORKFLOW_API + url, params
    ).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

// patch方法
export function patch (url, data = {}, header = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.CENTER_API + url,
      method: 'patch',
      data: encryptData(data),
      headers: header
    }).then(response => {
      if (store.state.isHttpEncrypt) {
        let re = {}
        Object.assign(re, response)
        if (re.data.result) {
          re.data.result = decryptData(re.data.result.data)
        } else {
          re.data = decryptData(re.data.data)
        }
        resolve(re)
      } else {
        resolve(response)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

// 流程部分的patch方法
export function basicWFPatch (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: $URL.WORKFLOW_API + url,
      method: 'patch',
      data
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

// 当执行事件采用的是http形式时(暂未使用)
export function httpAxios (url, method, data, params) {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      method: method,
      data: encryptData(data),
      params: params
    }).then(response => {
      if (store.state.isHttpEncrypt) {
        let re = {}
        Object.assign(re, response)
        if (re.data.result) {
          re.data.result = decryptData(re.data.result.data)
        } else {
          re.data = decryptData(re.data.data)
        }
        resolve(re)
      } else {
        resolve(response)
      }
    }).catch(error => {
      reject(error)
    })
  })
}
